package utils.jaxb;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.lang.StringUtils;

/**
 * <b>类描述：</b><br/>
 * <b>类名称：</b>XmlUtil<br/>
 * <b>创建人：</b><a href="mailto:yumin@nova.net.cn">余敏</a><br/>
 * <b>关键修改：</b><br/>
 * <b>修改时间：</b><br/>
 * <b>修改人：</b><br/>
 */
@XmlRegistry
public class XmlUtil {

	public static Object toBean(final String xmlString,Class beanclass) throws Exception {
		if (StringUtils.isEmpty(xmlString))
			throw new Exception("The input xml string is empty.");

		JAXBContext jc = JAXBContext
				.newInstance(beanclass);
		return jc.createUnmarshaller().unmarshal(
				new StreamSource(new StringReader(xmlString)));
	}

	public static String toXml(final Object bean) throws Exception {
		JAXBContext jc = JAXBContext
				.newInstance(bean.getClass());
		StringWriter sw = new StringWriter();
		jc.createMarshaller().marshal(bean, sw);
		return sw.toString();
	}

	public XmlUtil() {
	}

}
